package cn.com.controller;


import cn.com.beans.PAccount;
import cn.com.beans.PAccountRole;
import cn.com.beans.UserInfo;
import cn.com.mapper.PAccountMapper;
import cn.com.mapper.UserInfoMapper;
import cn.com.service.AccountInfoService;
import cn.com.service.PAccountRoleService;
import cn.com.service.PAccountService;
import cn.com.service.UserInfoService;
import cn.com.service.impl.EmailServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Random;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private PAccountService pAccountService;

    @Resource
    private PAccountMapper pAccountMapper;

    @Resource
    private EmailServiceImpl emailService;

    @Resource
    private PAccountRoleService pAccountRoleService;

    @GetMapping("/first")
    public String index() {
        return "first";
    }


    @GetMapping("/register")
    public String home() {
        return "register";
    }

    /**
     * 用户注册功能实现
     * @param model
     * @param req 前端输入得到的数据
     * @return
     */
    @PostMapping("/register")
    public String register(ModelMap model, HttpServletRequest req) {
        String name = req.getParameter("username");
        String sex = req.getParameter("select");
        String phone = req.getParameter("userPhone");
        if(pAccountService.selectByPhone(phone)) {
            req.setAttribute("msg","用户已存在");
            System.out.println("注册失败，用户已存在");
            return "register";
        }
        String email = req.getParameter("useremail");
        String pwd = req.getParameter("password");
//        md5加密

        UserInfo userInfo = new UserInfo();
        PAccount pAccount = new PAccount();
        PAccountRole pAccountRole = new PAccountRole();
        userInfo.setUName(name);
        userInfo.setUEmail(email);
        userInfo.setUSex(sex);
        userInfo.setUStatus(0);
        System.out.println("userInfo = " + userInfo);

//      设置account_info表里面的数据
        pAccount.setAccount(phone);
        pAccount.setPassword(pwd);
        pAccountRole.setRoleId(39);
        boolean b = userInfoService.insert(userInfo);
        boolean insert = pAccountService.insert(pAccount);
        int insert1 = pAccountRoleService.insert(pAccountRole);
        if(b && insert && insert1 > 0) {
            req.setAttribute("msg","注册成功");
            System.out.println("注册成功");
            return "first";
        }else {
            req.setAttribute("msg","用户名或密码错误");
            return "register";
        }
    }

    @GetMapping("/login")
    public String loginlogin() {
        return "login";
    }

    @PostMapping("/login")
    public String login (String userPhone,String password,HttpServletRequest req) {
        //String account = req.getParameter("userPhone");
        //String pwd = req.getParameter("password");
        Integer aId = pAccountMapper.selectByPhone(userPhone).get(0).getId();
        System.out.println("aId = " + aId);
        PAccount aif = new PAccount();
        aif.setId(aId);
        aif.setAccount(userPhone);
        aif.setPassword(password);
        if(pAccountService.selectByPhoneAndPwd(aif)) {
            List<PAccount> accountInfos = pAccountMapper.selectByPhone(userPhone);
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(aId);
            String username = userInfo.getUName();
            String province = userInfo.getUProvince();
            String level = userInfo.getULevel();
            Integer grade = userInfo.getUGrade();
            Integer ranking = userInfo.getURanking();
            Integer uAid = userInfo.getUAid();
            System.out.println("accountInfos = " + accountInfos);
            System.out.println("accountInfos.get(0).getAId() = " + accountInfos.get(0).getId());
            HttpSession session=req.getSession();//获取session并将userName存入session对象
            session.setAttribute("account", userPhone);
            session.setAttribute("uaid",uAid);
            session.setAttribute("username",username);
            session.setAttribute("grade",grade);
            session.setAttribute("province",province);
            session.setAttribute("level",level);
            session.setAttribute("ranking",ranking);
            req.setAttribute("msg","登录成功");
            System.out.println("登录成功");
            return "first";
        }else {
            req.setAttribute("msg","用户名或密码错误");
            return "login";
        }
    }

//    注销登录
    @RequestMapping("/loginout")
    public String loginOut(HttpServletRequest request) {
        System.out.println("进入了/loginout");
        request.getSession().invalidate();
        return "redirect:/user/first";
    }


    @GetMapping("/retrieve")
    public String retrieve() {
        return "retrieve";
    }

    @PostMapping("/retrieve")
    public String retrievepost(HttpServletRequest req,String userPhone,String password) {
        //String phone = req.getParameter("userPhone");
        //String pwd = req.getParameter("password");
        Integer aId = pAccountMapper.selectByPhone(userPhone).get(0).getId();
        PAccount accountInfo = new PAccount();
        accountInfo.setId(aId);
        accountInfo.setAccount(userPhone);
        accountInfo.setPassword(password);
        if(pAccountService.updateByPrimaryKey(accountInfo)>0) {
            System.out.println("修改新密码成功");
            req.setAttribute("msg","密码修改成功");
            return "login";
        }else {
            System.out.println("修改新密码失败");
            req.setAttribute("msg","密码修改失败");
            return "retrieve";
        }
    }

//  用户基本信息
    @GetMapping("/userinfo")
    public String userinfo(HttpServletResponse resp){

        return "userinfo";
    }

    @PostMapping("/userinfo")
    public String useruser(HttpServletRequest req,String province,String level,String grade,String ranking,HttpServletResponse resp) {
        Integer grade2 = Integer.parseInt(grade);
        Integer ranking2 = Integer.parseInt(ranking);
        HttpSession session = req.getSession();
        String account = (String)session.getAttribute("account");
        System.out.println("account === " + account);
        Integer aId = pAccountMapper.selectByPhone(account).get(0).getId();
        System.out.println("aId === " + aId);
        UserInfo u = userInfoMapper.selectByPrimaryKey(aId);
        System.out.println("u = " + u);
        u.setUProvince(province);
        u.setULevel(level);
        u.setUGrade(grade2);
        u.setURanking(ranking2);
        if(userInfoMapper.updateByPrimaryKey(u) > 0) {
            System.out.println("修改成功");
            req.setAttribute("msg","修改成功");
            return "first";
        }
        System.out.println("修改失败");
        req.setAttribute("msg","修改失败");
        return "userinfo";
    }

//    性格测试首页
    @GetMapping("/character")
    public String character() {
        return "character";
    }

//    进行性格测试
    @GetMapping("/occupation")
    public String oc() {
        return "occupation";
    }

    @PostMapping("/occupation")
    public String occu(HttpServletRequest req,HttpServletRequest resp) {
        Integer r1 = Integer.parseInt(req.getParameter("2"));
        Integer r2 = Integer.parseInt(req.getParameter("13"));
        Integer I1 = Integer.parseInt(req.getParameter("6"));
        Integer I2 = Integer.parseInt(req.getParameter("8"));
        Integer I3 = Integer.parseInt(req.getParameter("20"));
        Integer A1 = Integer.parseInt(req.getParameter("4"));
        Integer A2 = Integer.parseInt(req.getParameter("9"));
        Integer A3 = Integer.parseInt(req.getParameter("10"));
        Integer A4 = Integer.parseInt(req.getParameter("17"));
        Integer E1 = Integer.parseInt(req.getParameter("11"));
        Integer C1 = Integer.parseInt(req.getParameter("7"));
        Integer C2 = Integer.parseInt(req.getParameter("9"));
        int R = r1 + r2;
        int I = I1 + I2 + I3;
        int A = A1 + A2 + A3 + A4;
        int C = C1 + C2;
        System.out.println("R = " + R);
        System.out.println("I = " + I);
        System.out.println("A = " + A);
        System.out.println("C = " + C);
        if(A > R || A > I) {
            System.out.println("A型");
            return "A";
        }else if(R >= I || R >= A) {
            System.out.println("R型");
            return "R";
        }else if(C >= I || C >= A) {
            System.out.println("C型");
            return "C";
        }else {
            System.out.println("I型");
            return "I";
        }
    }

    @GetMapping("/occupation/A")
    public String A() {
        return "A";
    }
    @GetMapping("/occupation/I")
    public String I() {
        return "I";
    }
    @GetMapping("/occupation/R")
    public String R() {
        return "R";
    }
    @GetMapping("/occupation/C")
    public String C() {
        return "C";
    }

    //    判断账户是否存在
    @PostMapping("/exitphone")
    public void checkUser(HttpServletRequest req, HttpServletResponse resp)throws  IOException {
        PrintWriter out = resp.getWriter();
        String phone = req.getParameter("userPhone");
        if (phone.trim().equals("")) {
            out.print(2);// 号码为空
        } else {
            boolean b = pAccountService.selectByPhone(phone);
            System.out.println("b = " + b);
            if (b) {
                out.print(1);// 用户名存在
                return;
            } else {
                out.print(3);// 用户名不存在
                return;
            }
        }
    }

    //判断邮箱是否存在
    @PostMapping("/exitemail")
    public void checkemail(HttpServletRequest req, HttpServletResponse resp)throws  IOException {
        PrintWriter out = resp.getWriter();
        String email = req.getParameter("useremail");
        if (email.trim().equals("")) {
            out.print(2);// 号码为空
        }
        if(userInfoService.selectByemail(email)) {
            System.out.println("邮箱存在");
            out.print(1);
        }else {
            System.out.println("邮箱不存在");
            out.print(3);
        }
    }

//    判断电话号码和邮箱是不是一个人
    @PostMapping("/onepeople")
    public void checkonepeople(HttpServletRequest req, HttpServletResponse resp) {
        try {
            PrintWriter out = resp.getWriter();
            String phone = req.getParameter("userPhone");
            String email = req.getParameter("useremail");
            if(userInfoMapper.selectByEmail(email).size() >0) {
                Integer aId = pAccountMapper.selectByPhone(phone).get(0).getId();
                Integer uAid = userInfoMapper.selectByEmail(email).get(0).getUAid();
                if(aId.equals(uAid)) {
                    System.out.println("是同一个人");
                    out.print(1);
                }else {
                    System.out.println("不是同一个人");
                    out.print(2);
                }
            }else {
                System.out.println("不是同一个人");
                out.print(2);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//    从前端接收邮箱，并且发送验证码
    @PostMapping("/pushgetverification")
    public void pushgetverification(HttpServletRequest req,HttpServletResponse resp) {
        try {
            PrintWriter out = resp.getWriter();
            String email = req.getParameter("useremail");
            String number = req.getParameter("number");
            System.out.println("从前端接收的验证码是"+number);
            System.out.println("从前端接收的email是"+email);
            emailService.sendSimpleMail(email, number);
            System.out.println("邮箱发送成功");
            out.print(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
